<template>
	<view class="container">
		<!-- 状态标签页 -->
		<view class="status-tabs">
			<view class="tab-item" v-for="(tab, index) in tabs" :key="index" :class="{ active: currentTab === index }"
				@tap="switchTab(index)">
				<text class="tab-text">{{tab.name}}</text>
				<text class="tab-count">({{tab.count}})</text>
			</view>
		</view>

		<!-- 列表内容 -->
		<view class="signup-list">
			<view class="list-item" v-for="(item, index) in currentList" :key="index">
				<view class="user-info" @tap="goToProfile(item.userId)">
					<image class="avatar" :src="item.avatar || '/static/avatars/default-avatar.jpg'" mode="aspectFill">
					</image>
					<view class="info-content">
						<text class="nickname">{{item.nickName}}</text>
						<text class="signup-time">报名时间：{{formatTime(item.createTime)}}</text>
					</view>
				</view>

				<!-- 审批模式下显示操作按钮 -->
				<view class="action-buttons" v-if="mode === 'approval' && item.status === 'approving'">
					<button class="reject-btn" @tap="handleReject(item)">拒绝</button>
					<button class="approve-btn" @tap="handleApprove(item)">通过</button>
				</view>

				<!-- 显示状态标签 -->
				<view class="status-tag" :class="{
					'status-approved': item.status === 'approved',
					'status-pending': item.status === 'pending',
					'status-approving': item.status === 'approving',
					'status-rejected': item.status === 'rejected',
					'status-cancelled': item.status === 'cancelled'
				}">
					{{getStatusText(item.status)}}
				</view>
			</view>
		</view>

		<!-- 无数据提示 -->
		<view class="empty-tip" v-if="currentList.length === 0">
			<text>暂无{{tabs[currentTab].name}}记录</text>
		</view>
	</view>
</template>

<script>
	import {
		listSignups,
		updateSignups
	} from '@/api/youqiu/signups.js'

	export default {
		data() {
			return {
				activityId: '',
				mode: 'detail', // detail: 查看模式, approval: 审批模式
				createUserId: 0, //活动的创建人id
				currentTab: 0,
				signupList: [],
				isCreator: false, // 添加创建者标识
				tabs: [{ // 设置默认值，避免初始化时 undefined
					name: '已报名',
					status: 'approved',
					count: 0
				}]
			}
		},

		computed: {
			currentList() {
				// 添加安全检查
				if (!this.tabs || !this.tabs[this.currentTab]) {
					console.warn('当前标签页不存在:', this.currentTab)
					return []
				}

				const status = this.tabs[this.currentTab].status
				console.log('当前所有报名数据:', this.signupList)
				console.log('当前选中的状态:', status)

				// 添加数据安全检查
				if (!Array.isArray(this.signupList)) {
					console.warn('报名列表不是数组')
					return []
				}

				const filteredList = this.signupList.filter(item => {
					if (!item) {
						console.warn('存在无效的报名项')
						return false
					}
					console.log('比对项:', item.status, status, item.status === status)
					return item.status === status
				})

				console.log(`当前状态 ${status} 的过滤后数据:`, filteredList)
				return filteredList
			}
		},

		onLoad(options) {
			// 先初始化 tabs，再设置其他参数
			this.initTabs()

			if (options.id) {
				this.activityId = options.id
			}
			if (options.mode) {
				this.mode = options.mode
			}
			if (options.createUserId) {
				this.createUserId = options.createUserId
			}

			this.checkIsCreator()
			this.getList()
		},

		methods: {
			// 添加检查创建者方法
			checkIsCreator() {
				const userInfo = uni.getStorageSync('storage_data')?.vuex_user_info
				console.log('userInfo', userInfo)
				if (userInfo) {

					// 确保两个值都转换为数字类型进行比较
					const userId = Number(userInfo.userId)
					const createUserId = Number(this.createUserId)
					console.log('比较的值:', {
						userId,
						createUserId,
						'userId类型': typeof userId,
						'createUserId类型': typeof createUserId
					})
					this.isCreator = userId === createUserId
					console.log('this.isCreator', this.isCreator)
					// 重新初始化标签页
					this.initTabs()
				}
			},

			// 初始化标签页
			initTabs() {
				if (this.isCreator) {
					this.tabs = [{
							name: '已报名',
							status: 'approved',
							count: 0
						},
						{
							name: '待审批',
							status: 'approving',
							count: 0
						},
						{
							name: '待定',
							status: 'pending',
							count: 0
						},
						{
							name: '已拒绝',
							status: 'rejected',
							count: 0
						},
						{
							name: '请假',
							status: 'cancelled',
							count: 0
						}
					]
				} else {
					this.tabs = [{
							name: '已报名',
							status: 'approved',
							count: 0
						},
						{
							name: '待定',
							status: 'pending',
							count: 0
						},
						{
							name: '请假',
							status: 'cancelled',
							count: 0
						}
					]
				}
			},

			getList() {
				let data = {
					activityId: this.activityId
				}
				listSignups(data).then(res => {
					if (res.code === 200) {
						console.log('原始报名数据:', res.data)
						this.signupList = Array.isArray(res.data) ? res.data : []
						this.updateTabCounts()
						if (this.currentList.length === 0) {
							const tabWithData = this.tabs.findIndex(tab =>
								this.signupList.some(item => item.status === tab.status)
							)
							if (tabWithData !== -1) {
								this.currentTab = tabWithData
							}
						}
					}
				}).catch(err => {
					console.error('获取报名列表失败:', err)
					uni.showToast({
						title: '获取数据失败',
						icon: 'none'
					})
				})
			},

			updateTabCounts() {
				this.tabs.forEach(tab => {
					const count = this.signupList.filter(item => item.status === tab.status).length
					console.log(`${tab.name}状态数量:`, count)
					tab.count = count
				})
			},

			switchTab(index) {
				this.currentTab = index
			},

			getStatusText(status) {
				return {
					approved: '已报名',
					approving: '待审批',
					pending: '待定',
					rejected: '已拒绝',
					cancelled: '请假'
				} [status] || status
			},

			handleApprove(item) {
				uni.showModal({
					title: '确认通过',
					content: '确定通过该用户的报名申请吗？',
					success: (res) => {
						if (res.confirm) {
							updateSignups({
								id: item.id,
								status: 'approved'
							}).then(res => {
								if (res.code === 200) {
									uni.showToast({
										title: '已通过',
										icon: 'success'
									})
									this.getList()
								}
							})
						}
					}
				})
			},

			handleReject(item) {
				uni.showModal({
					title: '确认拒绝',
					content: '确定拒绝该用户的报名申请吗？',
					success: (res) => {
						if (res.confirm) {
							updateSignups({
								id: item.id,
								status: 'rejected'
							}).then(res => {
								if (res.code === 200) {
									uni.showToast({
										title: '已拒绝',
										icon: 'success'
									})
									this.getList()
								}
							})
						}
					}
				})
			},

			formatTime(timestamp) {
				if (!timestamp) return ''
				const date = new Date(timestamp)
				return `${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours()}:${date.getMinutes()}`
			},

			goToProfile(userId) {
				if (!userId) return
				uni.navigateTo({
					url: `/pages/profile/detail?userId=${userId}`
				})
			},

			getStatusCount(status) {
				return this.signupList.filter(item => item.status === status).length
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		min-height: 100vh;
		background: #f5f5f5;
		padding-bottom: 30rpx;
	}

	.status-tabs {
		display: flex;
		background: #fff;
		padding: 20rpx 30rpx;
		border-bottom: 1rpx solid #eee;
		overflow-x: auto;
		white-space: nowrap;

		/* 添加滚动条样式 */
		&::-webkit-scrollbar {
			display: none;
		}

		.tab-item {
			padding: 10rpx 30rpx;
			margin-right: 20rpx;
			border-radius: 30rpx;
			background: #f5f5f5;
			font-size: 28rpx;
			color: #666;
			flex-shrink: 0; // 防止标签被压缩

			&.active {
				background: #ff6b35;
				color: #fff;
			}

			.tab-text {
				display: inline-block; // 确保文本正确显示
			}

			.tab-count {
				font-size: 24rpx;
				margin-left: 4rpx;
				display: inline-block;
			}

			&:last-child {
				margin-right: 0; // 最后一个标签不需要右边距
			}
		}
	}

	.signup-list {
		padding: 20rpx;

		.list-item {
			background: #fff;
			border-radius: 12rpx;
			padding: 20rpx;
			margin-bottom: 20rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.user-info {
				display: flex;
				align-items: center;
				flex: 1;

				.avatar {
					width: 80rpx;
					height: 80rpx;
					border-radius: 50%;
					margin-right: 20rpx;
				}

				.info-content {
					flex: 1;

					.nickname {
						font-size: 28rpx;
						color: #333;
						margin-bottom: 8rpx;
						display: block;
					}

					.signup-time {
						font-size: 24rpx;
						color: #999;
					}
				}
			}

			.action-buttons {
				display: flex;
				align-items: center;
				margin-left: 20rpx;

				button {
					margin: 0 10rpx;
					font-size: 24rpx;
					padding: 8rpx 20rpx;
					border-radius: 30rpx;
					background: #fff;

					&.approve-btn {
						color: #fff;
						background: #ff6b35;
					}

					&.reject-btn {
						color: #666;
						border: 1rpx solid #ddd;
					}
				}
			}

			.status-tag {
				font-size: 24rpx;
				padding: 4rpx 16rpx;
				border-radius: 20rpx;

				&.status-approved {
					color: #52c41a;
					background: rgba(82, 196, 26, 0.1);
				}

				&.status-pending {
					color: #faad14;
					background: rgba(250, 173, 20, 0.1);
				}

				&.status-approving {
					color: #1890ff;
					background: rgba(24, 144, 255, 0.1);
				}

				&.status-rejected {
					color: #ff4d4f;
					background: rgba(255, 77, 79, 0.1);
				}

				&.status-cancelled {
					color: #666;
					background: rgba(0, 0, 0, 0.1);
				}
			}
		}
	}

	.empty-tip {
		text-align: center;
		padding: 100rpx 0;
		color: #999;
		font-size: 28rpx;
	}
</style>